package com.servlet;

import com.dao.BuildDao;
import com.dao.RoomDao;
import com.dao.UserDao;
import com.model.Build;
import com.model.PageBean;
import com.model.Room;
import com.model.User;
import com.util.DbUtil;
import com.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;

/**
 * 用户处理servlet,包含管理员与学生信息
 * @author : wangjg
 * @date : 2023/11/1 14:55
 */
@WebServlet(name = "UserServlet")
public class UserServlet extends HttpServlet {

    DbUtil dbUtil = new DbUtil();

    UserDao userDao = new UserDao();
    BuildDao buildDao = new BuildDao();
    RoomDao roomDao = new RoomDao();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        Object currentUserType = session.getAttribute("currentUserType");
        String searchText = request.getParameter("searchText");
        String buildId = request.getParameter("buildId");
        String searchType = request.getParameter("searchType");
        String page = request.getParameter("page");
        String action = request.getParameter("action");
        //是否为内部转发
        Object forward = request.getAttribute("forward");
        User user = new User();
        Connection con = null;
        try {
            con = dbUtil.getCon();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if("userinfo".equals(action)){
            getUserInfo(request, response);
            return;
        }else if("preSave".equals(action)) {
            studentPreSave(request, response);
            return;
        } else if("save".equals(action)){
            studentSave(request, response);
            return;
        } else if("delete".equals(action)){
            studentDelete(request, response);
            return;
        } else if("list".equals(action)) {
            if(StringUtil.isNotEmpty(searchText)) {
                if("name".equals(searchType)) {
                    user.setName(searchText);
                } else if("num".equals(searchType)) {
                    user.setNum(searchText);
                } else if("room".equals(searchType)) {
                    user.setRoomId(Integer.parseInt(searchText));
                }
            }
            if(StringUtil.isNotEmpty(buildId)) {
                if(forward == null){
                    user.setBuildId(Integer.parseInt(buildId));
                }
            }
            session.removeAttribute("searchText");
            session.removeAttribute("searchType");
            request.setAttribute("searchText", searchText);
            request.setAttribute("searchType", searchType);
        } else if("search".equals(action)){
            if(StringUtil.isNotEmpty(searchText)) {
                if("name".equals(searchType)) {
                    user.setName(searchText);
                } else if("num".equals(searchType)) {
                    user.setNum(searchText);
                } else if("roomNum".equals(searchType)) {
                    user.setRoomNum(searchText);
                }
                session.setAttribute("searchText", searchText);
                session.setAttribute("searchType", searchType);
            } else {
                session.removeAttribute("searchText");
                session.removeAttribute("searchType");
            }
            if(StringUtil.isNotEmpty(buildId)) {
                user.setBuildId(Integer.parseInt(buildId));
            }
        } else {
            if("admin".equals(currentUserType)) {
                if(StringUtil.isNotEmpty(searchText)) {
                    if("name".equals(searchType)) {
                        user.setName(searchText);
                    } else if("num".equals(searchType)) {
                        user.setNum(searchText);
                    } else if("roomNum".equals(searchType)) {
                        user.setRoomNum(searchText);
                    }
                    session.setAttribute("searchText", searchText);
                    session.setAttribute("searchType", searchType);
                }
                if(StringUtil.isNotEmpty(buildId)) {
                    user.setBuildId(Integer.parseInt(buildId));
                }
            }
        }
        if(StringUtil.isEmpty(page)) {
            page="1";
        }
        PageBean pageBean = new PageBean(Integer.parseInt(page), 5);
        request.setAttribute("pageSize", pageBean.getPageSize());
        request.setAttribute("page", pageBean.getPage());
        try {
            if("admin".equals(currentUserType)) {
                List<User> studentList = userDao.userList(con, pageBean,user);
                int total = userDao.userCount(con, user);
                String pageCode = this.genPage(total, Integer.parseInt(page),5);
                request.setAttribute("pageCode", pageCode);
                request.setAttribute("buildList", buildDao.buildList(con,null,new Build()));
                request.setAttribute("userList", studentList);
                request.setAttribute("studentList", studentList);
                request.setAttribute("mainPage", "admin/student.jsp");
                request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void studentSave(HttpServletRequest request,
                             HttpServletResponse response)throws ServletException, IOException {
        String userName = request.getParameter("name");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String num = request.getParameter("num");
        String sex = request.getParameter("sex");
        String tel = request.getParameter("tel");
        String userType = request.getParameter("userType");
        String roomId = request.getParameter("roomId");
        String buildId = request.getParameter("buildId");
        String studentId = request.getParameter("studentId");
        if(StringUtil.isNotEmpty(studentId)){
            System.out.println("开始修改学生信息：" + userName);
        }
        if(StringUtil.isEmpty(userType)){
            //用户类型为空的话默认赋值学生
            userType = "2";
        }
        Connection con = null;
        try {
            con = dbUtil.getCon();
            Build build = buildDao.buildInfo(con, Integer.parseInt(buildId));
            Room room = roomDao.roomInfo(con, Integer.parseInt(roomId));
            User student = new User(userName, password, name, num,sex, tel,room.getNum(),Integer.parseInt(roomId),
                    build.getName(),Integer.parseInt(buildId),Integer.parseInt(userType));
            int count;
            if(StringUtil.isNotEmpty(studentId)){
                student.setId(Integer.parseInt(studentId));
                count = userDao.updateUser(con,student);
                request.setAttribute("buildId",null);
            }else {
                count = userDao.addUser(con,student);
            }
            request.setAttribute("forward","true");
            if(count > 0) {
                request.getRequestDispatcher("user?action=list").forward(request, response);
            } else {
                request.setAttribute("student", student);
                request.setAttribute("error", "保存失败");
                request.setAttribute("mainPage", "admin/studentSave.jsp");
                request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void studentDelete(HttpServletRequest request,
                               HttpServletResponse response) {
        String studentId = request.getParameter("studentId");
        Connection con = null;
        try {
            con = dbUtil.getCon();
            userDao.deleteUser(con, studentId);
            request.getRequestDispatcher("user?action=list").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    private void getUserInfo(HttpServletRequest request,
                             HttpServletResponse response)throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User)(session.getAttribute("currentUser"));
        request.setAttribute("currentUser",user);
        request.setAttribute("mainPage", "student/userinfo.jsp");
        request.getRequestDispatcher("mainStudent.jsp").forward(request, response);
    }
    
    private void studentPreSave(HttpServletRequest request,
                                HttpServletResponse response)throws ServletException, IOException {
        String studentId = request.getParameter("studentId");
        Connection con = null;
        try {
            con = dbUtil.getCon();
            request.setAttribute("buildList", buildDao.buildList(con,null,new Build()));
            if (StringUtil.isNotEmpty(studentId)) {
                User student = userDao.userInfo(con, studentId);
                request.setAttribute("student", student);
                request.setAttribute("currentUser", student);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        request.setAttribute("mainPage", "admin/studentSave.jsp");
        request.getRequestDispatcher("mainAdmin.jsp").forward(request, response);
    }
    
    private String genPage(int totalNum, int currentPage, int pageSize){
        int totalPage = totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;
        StringBuilder pageCode = new StringBuilder();
        pageCode.append("<li><a href='user?page=1'>首页</a></li>");
        if(currentPage==1) {
            pageCode.append("<li class='disabled'><a href='#'>上一页</a></li>");
        }else {
            pageCode.append("<li><a href='user?page=").append(currentPage - 1).append("'>上一页</a></li>");
        }
        for(int i=currentPage-2;i<=currentPage+2;i++) {
            if(i<1||i>totalPage) {
                continue;
            }
            if(i==currentPage) {
                pageCode.append("<li class='active'><a href='#'>").append(i).append("</a></li>");
            } else {
                pageCode.append("<li><a href='user?page=").append(i).append("'>").append(i).append("</a></li>");
            }
        }
        if(currentPage==totalPage) {
            pageCode.append("<li class='disabled'><a href='#'>下一页</a></li>");
        } else {
            pageCode.append("<li><a href='user?page=").append(currentPage + 1).append("'>下一页</a></li>");
        }
        pageCode.append("<li><a href='user?page=").append(totalPage).append("'>尾页</a></li>");
        return pageCode.toString();
    }
}
